package org.yty.travelagencyredis.Dao.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.yty.travelagencyredis.Dao.ScenicSpotDao;
import org.yty.travelagencyredis.model.Entity.ScenicSpot;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class ScenicSpotDaoImpl implements ScenicSpotDao {
    private final StringRedisTemplate redisTemplate;

    @Override
    public List<ScenicSpot> selectAll() {
        List<Object> list = this.redisTemplate.opsForHash().values(ScenicSpot.key);
        return list.stream().map(item -> JSON.parseObject((String) item, ScenicSpot.class)).toList();
    }

    @Override
    public ScenicSpot selectById(Long id) {
        String scenicSpotJson = (String) this.redisTemplate.opsForHash().get(ScenicSpot.key, id);
        if (scenicSpotJson == null){
            return null;
        }
        return JSON.parseObject(scenicSpotJson, ScenicSpot.class);
    }

    @Override
    public boolean updateById(ScenicSpot scenicSpot) {
        this.redisTemplate.opsForHash().put(ScenicSpot.key, scenicSpot.getId(), JSON.toJSONString(scenicSpot));
        return true;
    }

    @Override
    public boolean insert(ScenicSpot scenicSpot) {
        this.redisTemplate.opsForHash().put(ScenicSpot.key, scenicSpot.getId(), JSON.toJSONString(scenicSpot));
        return true;
    }

    @Override
    public void deleteById(Long id) {
        this.redisTemplate.opsForHash().delete(ScenicSpot.key, id);
    }
}
